﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySqlCode.Properties;

namespace MySqlCode
{
    public partial class Main : Form
    {
        public Handler.MySQLHelper db { get; set; }
        public bool self = false;
        public string dbname;
        public string tbname;
        public string classCode;
        public string allPath;

        public Main()
        {
            InitializeComponent();
            db = new Handler.MySQLHelper(App.Database);
            var dbs = db.ShowDatabase();
            dbs.Insert(0, "----点击此处选择一个数据库进行操作----");
            cbxDatabases.DataSource = dbs;
        }
        // 窗体关闭
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!self) Application.Exit();
        }
        // 切换数据库
        private void tsmChange_Click(object sender, EventArgs e)
        {
            App.Database = null;
            Connector.GetInstance().Visible = true;
            self = true;
            this.Close();
        }
        // 退出按钮
        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        // 选择一个数据库时
        private void cbxDatabases_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbname = ((ComboBox)sender).SelectedItem.ToString();
            if (dbname != "----点击此处选择一个数据库进行操作----")
            {
                var tbs = db.ShowTables(dbname);
                tbs.Insert(0, "----全部表格----");
                tbs.Insert(0, "----请选择需要生成的表----");
                cbxTables.DataSource = tbs;
            }
            else cbxTables.DataSource = null;

            txtClassViewPackage.Text = $"com.{dbname}.model";
            txtDaoViewPackage.Text = $"com.{dbname}.dao";
            txtDBHelperViewPackage.Text = $"com.{dbname}.dal";
        }
        // 选择一个表时
        private void cbxTables_SelectionChangeCommitted(object sender, EventArgs e)
        {
            tbname = ((ComboBox)sender).SelectedItem.ToString();
        }
        // 关于按钮
        private void tsmAbout_Click(object sender, EventArgs e)
        {
            MessageBox.Show("by wiainigi@qq.com", "关于软件");
        }
        // 生成DBGelper代码预览
        private void btnDBHelper_Click(object sender, EventArgs e)
        {
            var ops = cbxDatabases.SelectedItem == null ? "" : cbxDatabases.SelectedItem.ToString();
            if (ops == "----点击此处选择一个数据库进行操作----")
            {
                MessageBox.Show("请选择一个数据库", "警告");
            }
            else
            {
                txtDBHelperCode.SelectionStart = 0;
                txtDBHelperCode.SelectionLength = txtDBHelperCode.Text.Length;
                txtDBHelperCode.SelectionColor = Color.Black;
                var code = Resources.DbHelperCode;
                code = code.Replace("[packageName]", txtDBHelperViewPackage.Text);
                code = code.Replace("[host]", App.Database.Host);
                code = code.Replace("[port]", App.Database.Port);
                code = code.Replace("[database]", dbname);
                code = code.Replace("[user]", App.Database.User);
                code = code.Replace("[password]", App.Database.Pwd);
                txtDBHelperCode.Text = code;
                Common.SetCodeColor(txtDBHelperCode);
            }
        }
        // 生成表对象代码预览
        private void btnClass_Click(object sender, EventArgs e)
        {
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----"
                || string.IsNullOrWhiteSpace(ops)
                || ops == "----全部表格----")
            {
                MessageBox.Show("请选择一个表", "警告");
            }
            else
            {
                txtClassCode.SelectionStart = 0;
                txtClassCode.SelectionLength = txtClassCode.Text.Length;
                txtClassCode.SelectionColor = Color.Black;
                var cols = db.AllFieldInfo(tbname);
                var pname = txtClassViewPackage.Text;
                var sb = Handler.Generate.ClassCode(cols, tbname, pname);
                classCode = sb.ToString();
                txtClassCode.Text = classCode;
                Common.SetCodeColor(txtClassCode);
            }
        }
        // 生成常用代码预览
        private void btnDao_Click(object sender, EventArgs e)
        {
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----"
                || string.IsNullOrWhiteSpace(ops)
                || ops == "----全部表格----")
            {
                MessageBox.Show("请选择一个表", "警告");
            }
            else
            {
                txtDaoCode.SelectionStart = 0;
                txtDaoCode.SelectionLength = txtDaoCode.Text.Length;
                txtDaoCode.SelectionColor = Color.Black;
                var cols = db.AllFieldInfo(tbname);
                var code = Resources.DaoCode;
                code = code.Replace("[self-packname]", txtDaoViewPackage.Text);
                code = code.Replace("[dal-packname]", txtDBHelperViewPackage.Text);
                code = code.Replace("[model-packname]", txtClassViewPackage.Text);
                code = code.Replace("[table]", tbname);
                code = code.Replace("[class-name]", tbname.PascalNaming());
                code = code.Replace("[update-values]", Handler.Generate.UpdateSetValues(cols));
                code = code.Replace("[update-params]", Handler.Generate.UpdateSetParams(cols));
                code = code.Replace("[field-yid]", Handler.Generate.FieldYesId(cols));
                code = code.Replace("[field-nid]", Handler.Generate.FieldNoId(cols));
                code = code.Replace("[insert-values]", Handler.Generate.InsertParams(cols));
                code = code.Replace("[insert-params]", Handler.Generate.InsertSetParams(cols));
                code = code.Replace("[set-model]", Handler.Generate.SetModel(cols));
                txtDaoCode.Text = code;
                Common.SetCodeColor(txtDaoCode);
            }
        }
        // 导出DBHelper
        private void tsmDownDBHelper_Click(object sender, EventArgs e)
        {
            var ops = cbxDatabases.SelectedItem == null ? "" : cbxDatabases.SelectedItem.ToString();
            if (ops == "----点击此处选择一个数据库进行操作----" || string.IsNullOrWhiteSpace(ops))
            {
                MessageBox.Show("选择一个数据库以便进行导出", "警告");
            }
            else
            {
                using (FolderBrowserDialog openDirectory = new FolderBrowserDialog())
                {
                    openDirectory.Description = "导出到哪个文件夹";
                    if (!string.IsNullOrWhiteSpace(allPath) || openDirectory.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrWhiteSpace(allPath) || !string.IsNullOrWhiteSpace(openDirectory.SelectedPath))
                        {
                            var path = (!string.IsNullOrWhiteSpace(allPath) ? allPath : openDirectory.SelectedPath) + $"/{txtDBHelperViewPackage.Text}";
                            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                            var code = Resources.DbHelperCode;
                            code = code.Replace("[packageName]", $"com.{dbname}.dal");
                            code = code.Replace("[host]", App.Database.Host);
                            code = code.Replace("[port]", App.Database.Port);
                            code = code.Replace("[database]", dbname);
                            code = code.Replace("[user]", App.Database.User);
                            code = code.Replace("[password]", App.Database.Pwd);
                            File.WriteAllText($"{path}/DBHelper.java", code);
                            if (string.IsNullOrWhiteSpace(allPath)) MessageBox.Show("导出成功", "提示");
                        }
                    }
                }
            }
        }
        // 导出表的类代码
        private void tsmDownATable_Click(object sender, EventArgs e)
        {
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----" || string.IsNullOrWhiteSpace(ops))
            {
                MessageBox.Show("选择一个表以便进行导出", "警告");
            }
            else
            {
                using (FolderBrowserDialog openDirectory = new FolderBrowserDialog())
                {
                    openDirectory.Description = "导出到哪个文件夹";
                    if (!string.IsNullOrWhiteSpace(allPath) || openDirectory.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrWhiteSpace(allPath) || !string.IsNullOrWhiteSpace(openDirectory.SelectedPath))
                        {
                            var path = (!string.IsNullOrWhiteSpace(allPath) ? allPath : openDirectory.SelectedPath) + $"/{txtClassViewPackage.Text}";
                            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                            if (ops == "----全部表格----")
                            {
                                var tables = db.ShowTables(dbname);
                                foreach (var tab in tables)
                                {
                                    var cols = db.AllFieldInfo(tab);
                                    var pname = txtClassViewPackage.Text;
                                    var sb = Handler.Generate.ClassCode(cols, tab, pname);
                                    File.WriteAllText($"{path}/{tab.PascalNaming()}Model.java", sb.ToString());
                                }
                            }
                            else
                            {
                                var cols = db.AllFieldInfo(tbname);
                                var pname = txtClassViewPackage.Text;
                                var sb = Handler.Generate.ClassCode(cols, tbname, pname);
                                File.WriteAllText($"{path}/{tbname.PascalNaming()}Model.java", sb.ToString());
                            }
                            if (string.IsNullOrWhiteSpace(allPath)) MessageBox.Show("导出成功", "提示");
                        }
                    }
                }
            }
        }
        // 导出表的常用代码
        private void tsmDownACode_Click(object sender, EventArgs e)
        {
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----" || string.IsNullOrWhiteSpace(ops))
            {
                MessageBox.Show("选择一个表以便进行导出", "警告");
            }
            else
            {
                using (FolderBrowserDialog openDirectory = new FolderBrowserDialog())
                {
                    openDirectory.Description = "导出到哪个文件夹";
                    if (!string.IsNullOrWhiteSpace(allPath) || openDirectory.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrWhiteSpace(allPath) || !string.IsNullOrWhiteSpace(openDirectory.SelectedPath))
                        {
                            var path = (!string.IsNullOrWhiteSpace(allPath) ? allPath : openDirectory.SelectedPath) + $"/{txtDaoViewPackage.Text}";
                            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                            if (ops == "----全部表格----")
                            {
                                var tables = db.ShowTables(dbname);
                                foreach (var tab in tables)
                                {
                                    var cols = db.AllFieldInfo(tab);
                                    var code = Resources.DaoCode;
                                    code = code.Replace("[self-packname]", txtDaoViewPackage.Text);
                                    code = code.Replace("[dal-packname]", txtDBHelperViewPackage.Text);
                                    code = code.Replace("[model-packname]", txtClassViewPackage.Text);
                                    code = code.Replace("[table]", tab.ToLower());
                                    code = code.Replace("[class-name]", tab.PascalNaming());
                                    code = code.Replace("[update-values]", Handler.Generate.UpdateSetValues(cols));
                                    code = code.Replace("[update-params]", Handler.Generate.UpdateSetParams(cols));
                                    code = code.Replace("[field-yid]", Handler.Generate.FieldYesId(cols));
                                    code = code.Replace("[field-nid]", Handler.Generate.FieldNoId(cols));
                                    code = code.Replace("[insert-values]", Handler.Generate.InsertParams(cols));
                                    code = code.Replace("[insert-params]", Handler.Generate.InsertSetParams(cols));
                                    code = code.Replace("[set-model]", Handler.Generate.SetModel(cols));
                                    File.WriteAllText($"{path}/{tab.PascalNaming()}Dao.java", code);
                                }
                            }
                            else
                            {
                                var cols = db.AllFieldInfo(tbname);
                                var code = Resources.DaoCode;
                                code = code.Replace("[self-packname]", txtDaoViewPackage.Text);
                                code = code.Replace("[dal-packname]", txtDBHelperViewPackage.Text);
                                code = code.Replace("[model-packname]", txtClassViewPackage.Text);
                                code = code.Replace("[table]", tbname);
                                code = code.Replace("[class-name]", tbname.PascalNaming());
                                code = code.Replace("[update-values]", Handler.Generate.UpdateSetValues(cols));
                                code = code.Replace("[update-params]", Handler.Generate.UpdateSetParams(cols));
                                code = code.Replace("[field-yid]", Handler.Generate.FieldYesId(cols));
                                code = code.Replace("[field-nid]", Handler.Generate.FieldNoId(cols));
                                code = code.Replace("[insert-values]", Handler.Generate.InsertParams(cols));
                                code = code.Replace("[insert-params]", Handler.Generate.InsertSetParams(cols));
                                code = code.Replace("[set-model]", Handler.Generate.SetModel(cols));
                                File.WriteAllText($"{path}/{tbname.PascalNaming()}Dao.java", code);
                            }
                            if (string.IsNullOrWhiteSpace(allPath)) MessageBox.Show("导出成功", "提示");
                        }
                    }
                }
            }
        }
        // 导出所选表的全部代码
        private void tsmDownAllCode_Click(object sender, EventArgs e)
        {
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----" || string.IsNullOrWhiteSpace(ops))
            {
                MessageBox.Show("选择一个表以便进行导出", "警告");
            }
            else
            {
                using (FolderBrowserDialog openDirectory = new FolderBrowserDialog())
                {
                    openDirectory.Description = "导出到哪个文件夹";
                    if (openDirectory.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrWhiteSpace(openDirectory.SelectedPath))
                        {
                            allPath = openDirectory.SelectedPath;
                            tsmDownACode.PerformClick();
                            tsmDownATable.PerformClick();
                            tsmDownDBHelper.PerformClick();
                            allPath = "";
                            MessageBox.Show("导出成功", "提示");
                        }
                    }
                }
            }
        }
        // 导出数据库代码
        private void tsmDownDatabase_Click(object sender, EventArgs e)
        {
            cbxTables.SelectedItem = "----全部表格----";
            var ops = cbxTables.SelectedItem == null ? "" : cbxTables.SelectedItem.ToString();
            if (ops == "----请选择需要生成的表----" || string.IsNullOrWhiteSpace(ops))
            {
                MessageBox.Show("选择一个数据库以便进行导出", "警告");
            }
            else
            {
                using (FolderBrowserDialog openDirectory = new FolderBrowserDialog())
                {
                    openDirectory.Description = "导出到哪个文件夹";
                    if (openDirectory.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrWhiteSpace(openDirectory.SelectedPath))
                        {
                            allPath = openDirectory.SelectedPath;
                            tsmDownACode.PerformClick();
                            tsmDownATable.PerformClick();
                            tsmDownDBHelper.PerformClick();
                            allPath = "";
                            MessageBox.Show("导出成功", "提示");
                        }
                    }
                }
            }
        }
        // 操作手册
        private void tsmTips_Click(object sender, EventArgs e)
        {
            MessageBox.Show(@"1、选择需要导出的数据库和表；
2、在预览界面中可以生成代码预览，可以复制；
3、使用菜单栏的【工具】按需导出代码。", "操作手册");
        }
    }
}
